Imports System.IO
Imports System.Xml.XPath

Public Class FileRequest
    Inherits Request

#Region "shared"

    Private Shared ReadOnly XPATH_IDENTIFIER As XPathExpression = XPathExpression.Compile("/request/item[@name = 'identifier']")
    Private Shared ReadOnly XPATH_SESSION_ID As XPathExpression = XPathExpression.Compile("/request/item[@name = 'session-id']")

    Private Shared Function GetIdentifier(ByVal xn) As String

        Dim xnX As XPathNavigator = xn.SelectSingleNode(XPATH_IDENTIFIER)
        If xnX Is Nothing Then
            Throw New ApplicationException("identifier expected")
        End If

        Return xnX.Value

    End Function

    Private Shared Function GetSessionId(ByVal xn) As String

        Dim xnX As XPathNavigator = xn.SelectSingleNode(XPATH_SESSION_ID)
        If xnX Is Nothing Then
            Throw New ApplicationException("session id expected")
        End If

        Return xnX.Value

    End Function
#End Region

#Region "instance"

    Private _Identifier As String
    Private _SessionId As String

    Public Sub New(ByVal xn As XPathNavigator, ByVal xmlStr As String)

        MyBase.New(xn, RequestType.File, xmlStr)

        _Identifier = GetIdentifier(xn)
        _SessionId = GetSessionId(xn)

    End Sub

    Public ReadOnly Property Identifier() As String
        Get
            Return _Identifier
        End Get
    End Property

    Public ReadOnly Property SessionId() As String
        Get
            Return _SessionId
        End Get
    End Property

    Protected Overrides Function DoResponse(ByVal r As System.Net.HttpWebResponse) As Response

        Dim resp As Response

        Dim filename As String
        ''begin: get filename
        'Dim cd As String = hr.Headers.Get("Content-Disposition")
        'Dim m As Match = FILENAME_REGEX.Match(cd)
        'If m.Success Then
        '    filename = m.Groups("filename").Value
        'Else
        '    filename = ""
        'End If
        ''end:get filename
        filename = Path.GetFileName(_Identifier)

        resp = New FileResponse(filename, r.GetResponseStream)

        Return resp

    End Function
#End Region
End Class
